<?php
namespace app\admin2\controller;

use app\common\model\WxUser as WxUserModel;
use app\common\model\AuthorWxUser as AuthorWxUserModel;
use app\common\model\Users as UsersModel;
use app\common\util\WechatThirdUtil;
use app\common\controller\AdminBaseo;
use htq\HTQClient; //队列类
use think\Session;
use think\Db;

class Sync extends AdminBaseo
{   
    protected $wechat_obj;
    protected $author_wx_user;
    protected $author_wx_user_model;
    protected $wx_user;
    protected $users_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->wx_user = new WxUserModel();
        $this->author_wx_user_model = new AuthorWxUserModel;
        $this->author_wx_user = Session::get('wechat_info');
        $this->config = $this->wx_user->find();//第三方平台
        $this->wechat_obj = new WechatThirdUtil($this->config , $this->author_wx_user);
    }

    public function syncPubInfo(){
        //获取授权公众号基本信息
        $base_info = $this->wechat_obj->getAuthorizerInfo();
        $wechat_base_info = $base_info['authorizer_info'];
        $data = [
            'wxname'                   => $wechat_base_info['nick_name'],   //微信公众号名字
            'headerpic'                => isset($wechat_base_info['head_img']) ? $wechat_base_info['head_img'] : '', //微信公众号头像
            'type'                     => $wechat_base_info['service_type_info']['id'], //微信公众号类型
            'verify_type'              => $wechat_base_info['verify_type_info'], //授权方认证类型
            'weixin'                   => isset($wechat_base_info['alias']) ? $wechat_base_info['alias'] : '', //微信号
            'qr'                       => $wechat_base_info['qrcode_url'], //二维码图片的URL
            'idc'                      => $wechat_base_info['idc'],
            'principal_name'           => $wechat_base_info['principal_name'], //公众号的主体名称
            'signature'                => $wechat_base_info['signature'], //公众号的主体名称
            'business_info'            => serialize($wechat_base_info['business_info']), //功能
            'funcscope_category'       => serialize($base_info['authorization_info']['func_info']), //授权给开发者的权限集列表
        ];

        $result = $this->author_wx_user_model->save($data,['appid'=>$base_info['authorization_info']['authorizer_appid'],'authorized'=>1]);
        if($result){
            $this->author_wx_user['wxname'] = $data['wxname'];
            $this->author_wx_user['headerpic'] = $data['headerpic'];
            $this->author_wx_user['type'] = $data['type'];
            $this->author_wx_user['verify_type'] = $data['verify_type'];
            $this->author_wx_user['weixin'] = $data['weixin'];
            $this->author_wx_user['qr'] = $data['qr'];
            $this->author_wx_user['idc'] = $data['idc'];
            $this->author_wx_user['principal_name'] = $data['principal_name'];
            $this->author_wx_user['signature'] = $data['signature'];
            $this->author_wx_user['business_info'] = $data['business_info'];
            $this->author_wx_user['funcscope_category'] = $data['funcscope_category'];
            Session::set('wechat_info' , $this->author_wx_user);

            return json(['status' => 1,'msg'=>'ok']);
        } else {
            return json(['status' => -1,'msg'=>'sync failed']);
        }
    }

    /**
     * 同步粉丝信息
     */
    public function queue(){
        $queue_name = 'syncFans_'.date('Ymd').'_'.session::get('admin_id').date('His').rand(1,9999);
        $template_msg['queue_name'] = $queue_name;
        $url = QUEUE_URL.'/api/Sync/syncFansInfo/id/'.$this->author_wx_user['id'];
        $ret = $this->HTQClient->addQueue($queue_name,"real_time");
        if($ret['error_code'] == 1002){
            //队列已存在请重新操作
            return false;
        }
        $result = $this->HTQClient->addTask($queue_name,$url,$template_msg);
        if($result['error_code'] == 0){
            //队列任务添加成功
            return json(['status' => 1 ,'msg' => 'ok']);
        }else if($result['error_code'] == 1001){
            //队列任务添加失败
            return false;
        }
    }


    /**
     * 同步粉丝信息
     */
    public function syncFansInfo(){
        $arr = $this->wechat_obj->getFanIdList();
        if($arr['total'] != 0){
                $j = $arr['total'] / $arr['count'];
                for($i = 0; $i < $j; $i++){
                    $chunk_arr = array_chunk($arr['data']['openid'],100);
                    foreach($chunk_arr as $v){
                        $openid_list = [];
                        foreach($v as $v2){
                            $openid_list[] = ['openid' => $v2];
                        }
                        $data = $this->wechat_obj->getBatchget($openid_list);
                        foreach($data['user_info_list'] as $user){
                            // dump($user['openid']);exit();
                            $this->users_model = new UsersModel;
                            $openid = $this->users_model->where('openid',$user['openid'])->value('openid');
                            if($openid){
                                $this->users_model->save($user,['openid' => $openid]);
                            }else{
                                $this->users_model = new UsersModel;
                                $this->users_model->save($user);
                            }
                        }
                    }
                    if($j > $i){
                        $arr = $this->wechat_obj->getFanIdList($arr['next_openid']);
                    }
                }
                return json(['status' => 1,'msg'=>'ok']);
        }
    }
}